<?php
namespace app\admin\controller\product;

use app\admin\model\Product;
use app\common\controller\Backend;
use think\Db;
use think\Exception;


class Index extends Backend
{
    protected $model = null;
    protected $noNeedRight = [];
    protected $searchFields = ['name'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Product();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            $this->request->get(['filter' => json_encode($filterArr)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $whereNew = [
                'is_delete' => 0
            ];
            $list = $this->model
                ->where($mimetypeQuery)
                ->where($where)
                ->where($whereNew)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $subData = $this->request->param();
            $subData['row']['admin_id'] = $this->auth->id;
            $result = $this->model->allowField(true)->save($subData['row']);
            if (!$result) {
                $this->error('提交失败');
            }
            $this->success(' 提交成功');
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function addPDF()
    {
        if ($this->request->isPost()) {
            $subData = $this->request->param();
            $subData['row']['admin_id'] = $this->auth->id;
            $result = $this->model->allowField(true)->save($subData['row']);
            if (!$result) {
                $this->error('提交失败');
            }
            $this->success(' 提交成功');
        }

        var_dump(11);exit;
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = "")
    {
        if ($this->request->isPost()) {
            $subData = $this->request->param();
            if ($this->auth->id != $this->model->where(['id' => $subData['row']['id']])->value('admin_id')) {
                $this->error('该产品您无法操作');
            }
            $result = $this->model->allowField(true)->isUpdate(true)->save($subData['row']);
            if (!$result) {
                $this->error('提交失败');
            }
            $this->success(' 提交成功');
        }

        $detail = $this->model->find($ids);
        $this->assign('detail', $detail);

        return $this->view->fetch();
    }


    /**
     * 删除
     * @param array $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $lists = $this->model->where('id', 'in', $ids)->select();
            Db::startTrans();
            try {
                foreach ($lists as $list) {
                    if ($list->admin_id != $this->auth->id) {
                        throw new Exception("该产品【{$list->name}】您无法删除");
                    }
                    $this->model->where(['id' => $list->id])->update(['is_delete' => 1,'deletetime' => time()]);
                }
            }catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            Db::commit();

            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * import方法
     */
    public function import()
    {
        $file = $this->request->request('file'); //'file'为文件字段名
        $data = $this->readFile($file);

        foreach ($data as $key => $row){
            if ($key == 0) continue;
            if (empty($row['产品名称']) && empty($row['产品规格']) && empty($row['尺寸要求/图号'])) continue;
            $subData[] = [
                'name' => $row['产品名称'],
                'spec' => $row['产品规格'],
                'size' => $row['尺寸要求/图号'],
//                'height' => $row['高度'],
//                'width' => $row['宽度'],
                'createtime' => time(),
                'updatetime' => time(),
                'admin_id' => $this->auth->id,
            ];
        }

        if (empty($subData)) {
            $this->error('导入数据为空');
        }
        $this->model->insertAll($subData);
        $this->success('导入成功');
    }

//    public function select()
//    {
//        $lists = $this->
//        return $this->view->fetch();
//    }
}